package com.wyzz.hr.bo.impl;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.log4j.Logger;
import org.hibernate.criterion.*;

import com.wyzz.hr.base.BaseAction;
import com.wyzz.hr.bo.IAttdoriginaldataBO;
import com.wyzz.hr.bo.IEmployeeBo;
import com.wyzz.hr.bo.IEmpshiftBo;
import com.wyzz.hr.bo.IMachineBO;
import com.wyzz.hr.bo.IOvertimerequestBo;
import com.wyzz.hr.bo.MachineBOFactory;
import com.wyzz.hr.dao.IAttdoriginaldataDAO;
import com.wyzz.hr.pojo.AttdMachine;
import com.wyzz.hr.pojo.AttdSyncRecord;
import com.wyzz.hr.pojo.Attdoriginaldata;
import com.wyzz.hr.pojo.Attendshift;
import com.wyzz.hr.pojo.Employee;
import com.wyzz.hr.spring.SpringBeanFactory;
import com.wyzz.hr.util.BaseCrit;
import com.wyzz.hr.util.DatabaseSysConfigManager;
import com.wyzz.hr.util.DateUtil;
import com.wyzz.hr.util.Pager;
import com.wyzz.hr.util.SysConfigManager;

public class AttdoriginaldataBOImpl implements IAttdoriginaldataBO {

	public AttdoriginaldataBOImpl() {
	}

	public boolean addAttdoriginaldata(Attdoriginaldata data) {
		try {
			attdoriginaldataDAO.saveObject(data);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return false;
	}

	public boolean deleteAttdoriginaldata(String aodIds) {
		if (aodIds == null || aodIds.trim().length() == 0)
			return true;
		try {
			String hql = (new StringBuilder()).append(
					"delete from Attdoriginaldata where aodId in (").append(
					aodIds).append(")").toString();
			attdoriginaldataDAO.exeHql(hql);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	public Map changeNightShift(String aodIds, Integer type) {
		Map returnMap = new HashMap();
		if (aodIds == null || aodIds.length() == 0)
			return returnMap;
		String idArr[] = aodIds.split(",");
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Attdoriginaldata.class);
		dc.add(Restrictions.in(Attdoriginaldata.PROP_AOD_ID, idArr));
		List dataList = attdoriginaldataDAO.findByCriteria(dc);
		for (int i = 0; dataList != null && i < dataList.size(); i++) {
			Attdoriginaldata data = (Attdoriginaldata) dataList.get(i);
			Integer currentType = checkDateAndCardTime(data.getAodAttdDate(),
					data.getAodCardTime());
			if (currentType.intValue() == type.intValue())
				continue;
			if (type.intValue() == 0)
				data.setAodAttdDate(DateUtil.convDateTimeToDate(data
						.getAodCardTime()));
			if (type.intValue() == 1)
				data
						.setAodAttdDate(DateUtil.dateAdd(data.getAodAttdDate(),
								-1));
			returnMap.put(data.getAodId(), DateUtil.formatDate(data
					.getAodAttdDate()));
		}

		attdoriginaldataDAO.saveOrupdate(dataList);
		return returnMap;
	}

	public Integer checkDateAndCardTime(Date aodDate, Date aodCardTime) {
		String dateStr = DateUtil.formatDate(aodDate);
		String cardStr = DateUtil.formatDate(aodCardTime);
		if (dateStr.equals(cardStr))
			return Integer.valueOf(0);
		else
			return Integer.valueOf(1);
	}

	public Attdoriginaldata getAttdoriginaldata(String aodId) {
		return (Attdoriginaldata) attdoriginaldataDAO.loadObject(
				com.wyzz.hr.pojo.Attdoriginaldata.class, aodId, null,
				new boolean[0]);
	}

	public boolean saveAttdoriginaldata(Attdoriginaldata data) {
		attdoriginaldataDAO.saveOrupdate(data);
		return true;
	}

	public boolean insertDataList(List dataList, Date cardStartDate,
			Date cardEndDate) {
		if (dataList.size() == 0)
			return true;
		IEmpshiftBo empshiftBo = (IEmpshiftBo) SpringBeanFactory
				.getBean("empshiftBO");
		IOvertimerequestBo or_BO = (IOvertimerequestBo) SpringBeanFactory
				.getBean("overtimerequestBO");
		Date beforeDate = DateUtil.dateAdd(DateUtil
				.convDateTimeToDate(cardStartDate), -1);
		cardEndDate = DateUtil.convDateTimeToDate(cardEndDate);
		Map sysMap = DatabaseSysConfigManager.getInstance().getProperties();
		String startMinute = (String) sysMap.get("sys.shift.start.minute");
		String endMinute = (String) sysMap.get("sys.shift.end.minute");
		List emps = getEmps(dataList);
		String empIds[] = new String[emps.size()];
		for (int i = 0; emps != null && i < emps.size(); i++)
			empIds[i] = ((Employee) emps.get(i)).getId();

		Map existShiftMap = empshiftBo.provideEmpShiftData(empIds, beforeDate,
				cardEndDate);
		empshiftBo.provideDefaultShift(existShiftMap, beforeDate, cardEndDate,
				emps);
		Map empOrMap = or_BO.provideOvertimeRequestData(beforeDate,
				cardEndDate, emps);
		for (Date idate = beforeDate; idate.getTime() <= cardEndDate.getTime(); idate = DateUtil
				.dateAdd(idate, 1)) {
			for (int i = 0; emps != null && i < emps.size(); i++) {
				Employee emp = (Employee) emps.get(i);
				String key = (new StringBuilder()).append(emp.getId()).append(
						DateUtil.formatDate(idate)).toString();
				Attendshift shift = (Attendshift) existShiftMap.get(key);
				if (shift == null) {
					shift = new Attendshift(null, "\u52A0\u73ED", null, null,
							null);
					existShiftMap.put(key, shift);
				}
				shift.setNewAttdSession(shift.getAttsSession());
				shift.setNewAttdNightShift(shift.getAttsNightShift());
				empshiftBo.changeAttdSessionWithOR(idate, shift,
						(List) empOrMap.get((new StringBuilder()).append(
								emp.getId()).append(DateUtil.formatDate(idate))
								.toString()));
			}

		}

		Attendshift shift = null;
		Date lastDate = null;
		Iterator i$ = dataList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Attdoriginaldata data = (Attdoriginaldata) i$.next();
			lastDate = DateUtil.dateAdd(data.getAodAttdDate(), -1);
			shift = (Attendshift) existShiftMap.get((new StringBuilder())
					.append(data.getAttdEmp().getId()).append(
							DateUtil.formatDate(lastDate)).toString());
			if (shift != null && shift.getNewAttdNightShift() != null
					&& shift.getNewAttdNightShift().intValue() != 0) {
				String cut[] = shift.getNewAttdSession().split(",");
				Date onTime = DateUtil.parseDateByFormat((new StringBuilder())
						.append(DateUtil.formatDateToS(lastDate, "yyyy-MM-dd"))
						.append(" ").append(cut[0].split("-")[0]).toString(),
						"yyyy-MM-dd HH:mm");
				Date offTime = DateUtil.parseDateByFormat((new StringBuilder())
						.append(DateUtil.formatDateToS(lastDate, "yyyy-MM-dd"))
						.append(" ").append(cut[cut.length - 1].split("-")[1])
						.toString(), "yyyy-MM-dd HH:mm");
				Date onTime_b = DateUtil.dateTimeAdd(onTime, 0 - Integer
						.parseInt(startMinute), 12);
				Date offTime_a = DateUtil.dateTimeAdd(offTime, Integer
						.parseInt(endMinute), 12);
				if (onTime_b.getTime() <= data.getAodCardTime().getTime()
						&& data.getAodCardTime().getTime() <= offTime_a
								.getTime())
					data.setAodAttdDate(lastDate);
			}
		} while (true);
		attdoriginaldataDAO.saveOrupdate(dataList);
		return true;
	}

	private List getEmps(List dataList) {
		List emps = new ArrayList();
		Attdoriginaldata data;
		for (Iterator i$ = dataList.iterator(); i$.hasNext(); emps.add(data
				.getAttdEmp()))
			data = (Attdoriginaldata) i$.next();

		return emps;
	}

	public List searchOriginalDataList(DetachedCriteria dc, Pager page,
			Attdoriginaldata searchBean) {
		dc.createAlias(Attdoriginaldata.PROP_AOD_EMP_NO, "emp", 1);
		dc.createAlias((new StringBuilder()).append("emp.").append(
				Employee.PROP_EMP_DEPT_NO).toString(), "empDeptNo", 1);
		if (searchBean.getAttdEmp() != null)
			BaseCrit.addEmpDC(dc, "emp", searchBean.getAttdEmp().getEmpName());
		if (searchBean.getAttdEmp() != null
				&& searchBean.getAttdEmp().getEmpDeptNo() != null)
			BaseCrit
					.addDeptDC(dc, (new StringBuilder()).append("emp.").append(
							Employee.PROP_EMP_DEPT_NO).toString(),
							(new StringBuilder()).append("emp.").append(
									Employee.PROP_EMP_PB_NO).toString(),
							Integer.valueOf(1), searchBean.getAttdEmp()
									.getEmpDeptNo());
		BaseCrit.addDC(dc, Attdoriginaldata.PROP_AOD_TTD_MACHINE_NO, "eq",
				new String[] { searchBean.getAodTtdMachineNo() });
		BaseCrit.addDCDateRange(dc, Attdoriginaldata.PROP_AOD_ATTD_DATE,
				searchBean.getStartDate(), searchBean.getEndDate());
		BaseCrit.addDC(dc, Attdoriginaldata.PROP_AOD_STATUS, "eq",
				new Integer[] { searchBean.getAodStatus() });
		if (searchBean.getAodNightStatus() != null
				&& searchBean.getAodNightStatus().intValue() == 0)
			dc.add(Restrictions
					.sqlRestriction("aod_attd_date=date(aod_card_time)"));
		else if (searchBean.getAodNightStatus() != null
				&& searchBean.getAodNightStatus().intValue() == 1)
			dc.add(Restrictions
					.sqlRestriction("aod_attd_date<>date(aod_card_time)"));
		if (searchBean.getBeginHour() > 0.0F || searchBean.getEndHour() < 24F)
			dc.add(Restrictions.sqlRestriction((new StringBuilder()).append(
					"hour(aod_card_time)*60+minute(aod_card_time)>=").append(
					searchBean.getBeginHour() * 60F).append(
					"and hour(aod_card_time)*60+minute(aod_card_time)<=")
					.append(searchBean.getEndHour() * 60F).toString()));
		BaseCrit.addDC(dc, Attdoriginaldata.PROP_AOD_MEMO, "like",
				new String[] { searchBean.getAodMemo() });
		BaseAction.addOrders(dc, page,
				new String[] {
						(new StringBuilder()).append(
								Attdoriginaldata.PROP_AOD_CARD_TIME).append(
								"-down").toString(),
						(new StringBuilder()).append("emp.").append(
								Employee.PROP_EMP_DISTINCT_NO).append("-up")
								.toString() });
		page.splitPage(dc);
		return attdoriginaldataDAO.findByCriteria(dc, page.getPageSize(), page
				.getCurrentPage());
	}

	public boolean deleteDataInDateDomain(Date dateFrom, Date dateTo) {
		Format format = new SimpleDateFormat("yyyy-MM-dd");
		String dateFrom1 = format.format(dateFrom);
		String dateTo1 = format.format(dateTo);
		String hql = (new StringBuilder()).append(
				"delete Attdoriginaldata where aodAttdDate >= '").append(
				dateFrom1).append("' and aodAttdDate <= '").append(dateTo1)
				.append("'").toString();
		attdoriginaldataDAO.exeHql(hql);
		return true;
	}

	public boolean saveOriginalData(String empNo[], Date attdDate,
			Date attdCardTime, String aodTtdMachineNo, String memo,
			String currentEmpName) {
		List dataList = new ArrayList();
		IEmployeeBo esaBo = (IEmployeeBo) SpringBeanFactory.getBean("empBo");
		List empList = esaBo.searchEmpArray(empNo);
		Attdoriginaldata data;
		for (Iterator i$ = empList.iterator(); i$.hasNext(); dataList.add(data)) {
			Employee emp = (Employee) i$.next();
			data = new Attdoriginaldata();
			data.setAodId((new StringBuilder()).append(emp.getId()).append(
					DateUtil.formatDateToS(attdCardTime, "yyyyMMddHHmmss"))
					.toString());
			data.setAttdEmp(emp);
			data.setAodCardTime(attdCardTime);
			data.setAodEmpDistinctNo(emp.getEmpDistinctNo());
			data.setAodAttdDate(attdDate);
			data.setAodTtdMachineNo(aodTtdMachineNo);
			data.setAodStatus(Integer.valueOf(0));
			data.setAodLastModifyUser(currentEmpName);
			data.setAodLastModifyTime(new Date());
			data.setAodStatus(Integer.valueOf(1));
			data.setAodMemo(memo);
		}

		attdoriginaldataDAO.saveOrupdate(dataList);
		return true;
	}

	public IAttdoriginaldataDAO getAttdoriginaldataDAO() {
		return attdoriginaldataDAO;
	}

	public void setAttdoriginaldataDAO(IAttdoriginaldataDAO attdoriginaldataDAO) {
		this.attdoriginaldataDAO = attdoriginaldataDAO;
	}

	private void checkOrderMethod(DetachedCriteria detachedCriteria,
			String order) {
		if (order != null && order.trim().length() > 1
				&& order.indexOf('-') != -1) {
			String pram[] = order.split("-");
			if (pram[0] == null || pram[0].length() < 1)
				return;
			String orde = pram[0];
			if (pram.length == 2 && pram[1].equalsIgnoreCase("up"))
				detachedCriteria.addOrder(Order.asc(orde));
			else
				detachedCriteria.addOrder(Order.desc(orde));
		} else {
			detachedCriteria.addOrder(Order.asc("attdEmp.empName"));
		}
	}

	public List provideOriginalDataList(Date startDate, Date endDate, List emps) {
		DetachedCriteria dc = DetachedCriteria
				.forClass(com.wyzz.hr.pojo.Attdoriginaldata.class);
		if (emps.size() > 0 && emps.size() <= 500)
			dc.add(Restrictions.in("attdEmp", emps));
		dc.add(Restrictions.ge(Attdoriginaldata.PROP_AOD_ATTD_DATE, startDate));
		dc.add(Restrictions.le(Attdoriginaldata.PROP_AOD_ATTD_DATE, endDate));
		dc.addOrder(Order.asc(Attdoriginaldata.PROP_AOD_CARD_TIME));
		List resultList = attdoriginaldataDAO.findByCriteria(dc);
		return resultList;
	}

	public Map provideOriginalDataMap(Date startDate, Date endDate, List emps) {
		List resultList = provideOriginalDataList(startDate, endDate, emps);
		Map origEmpDateMap = new HashMap();
		String key = null;
		List tempList = null;
		Attdoriginaldata data;
		for (Iterator i$ = resultList.iterator(); i$.hasNext(); tempList
				.add(data)) {
			data = (Attdoriginaldata) i$.next();
			key = (new StringBuilder()).append(data.getAttdEmp().getId())
					.append(DateUtil.formatDate(data.getAodAttdDate()))
					.toString();
			tempList = (List) origEmpDateMap.get(key);
			if (tempList == null) {
				tempList = new ArrayList();
				origEmpDateMap.put(key, tempList);
			}
		}

		return origEmpDateMap;
	}

	public void insertAttdoriginalData(List recordList, List dataList,
			AttdMachine machine) {
		Date startDate = null;
		Date endDate = null;
		List resultList = new ArrayList();
		Map map = recordListToMap(recordList);
		Iterator i$ = dataList.iterator();
		do {
			if (!i$.hasNext())
				break;
			Attdoriginaldata data = (Attdoriginaldata) i$.next();
			if (data.getAodEmpDistinctNo() != null) {
				Employee emp = (Employee) map.get(data.getAodEmpDistinctNo());
				if (emp != null) {
					resultList.add(data);
					data.setAodTtdMachineNo(machine.getMacNo());
					if (startDate == null) {
						startDate = data.getAodAttdDate();
						endDate = data.getAodAttdDate();
					}
					if (data.getAodAttdDate().compareTo(startDate) < 0)
						startDate = data.getAodAttdDate();
					if (data.getAodAttdDate().compareTo(endDate) > 0)
						endDate = data.getAodAttdDate();
				}
			}
		} while (true);
		insertDataList(resultList, startDate, endDate);
	}

	private Map recordListToMap(List recordList) {
		Map map = new HashMap();
		AttdSyncRecord record;
		for (Iterator i$ = recordList.iterator(); i$.hasNext(); map.put(record
				.getAsrEmp().getEmpDistinctNo(), record.getAsrEmp()))
			record = (AttdSyncRecord) i$.next();

		return map;
	}

	public String batchReadRecord(List recordList, List attdMachineList,
			Date dateFrom, Date dateTo) {
		SysConfigManager dbConfigManager = DatabaseSysConfigManager
				.getInstance();
		String autoSyncTime = dbConfigManager
				.getProperty("sys.examin.machinetime.autosync");
		String result = "";
		for (Iterator i$ = attdMachineList.iterator(); i$.hasNext();) {
			AttdMachine attdMachine = (AttdMachine) i$.next();
			List machineRecord = new ArrayList();
			i$ = recordList.iterator();
			do {
				if (!i$.hasNext())
					break;
				AttdSyncRecord record = (AttdSyncRecord) i$.next();
				if (record.getAsrAttdMachine().getMacId().equals(
						attdMachine.getMacId()))
					machineRecord.add(record);
			} while (true);
			if (machineRecord.isEmpty()) {
				result = (new StringBuilder())
						.append(result)
						.append("\u6CA1\u6709\u8003\u52E4\u673A")
						.append(attdMachine.getMacNo())
						.append(
								"\u7684\u540C\u6B65\u8BB0\u5F55\uFF01no AttdSyncRecord!\n")
						.toString();
			} else {
				if (!result.equals(""))
					result = (new StringBuilder()).append(result).append("  ")
							.toString();
				IMachineBO machineBO = MachineBOFactory
						.getMachineBO(attdMachine.getMacClass());
				int errorCode = machineBO.connectNet(attdMachine);
				if (errorCode != machineBO.getSuccCode()) {
					result = (new StringBuilder()).append(result).append(
							attdMachine.getMacNo()).append(
							"\u8FDE\u63A5\u5931\u8D25\uFF1A").append(
							machineBO.getErrorByCode(errorCode)).append("\n")
							.toString();
				} else {
					result = (new StringBuilder())
							.append(result)
							.append(
									"\u8FDE\u63A5\u8003\u52E4\u673A connect to ")
							.append(attdMachine.getMacNo())
							.append(
									" \u6210\u529F\uFF0C\u5F00\u59CB\u8BFB\u53D6.......\n")
							.toString();
					List resultList = machineBO.getAllCardData(machineRecord,
							dateFrom, dateTo);
					if ("1".equals(autoSyncTime))
						if (!machineBO.syncMachineTime())
							result = (new StringBuilder())
									.append(result)
									.append(
											"\u540C\u6B65\u8003\u52E4\u673A\u65F6\u95F4(sync machine time)\u5931\u8D25\uFF01\n")
									.toString();
						else
							result = (new StringBuilder())
									.append(result)
									.append(
											"\u540C\u6B65\u8003\u52E4\u673A\u65F6\u95F4(sync machine time)\u6210\u529F\uFF01\n")
									.toString();
					machineBO.disConnectNet();
					insertAttdoriginalData(recordList, resultList, attdMachine);
					result = (new StringBuilder())
							.append(result)
							.append(
									"\u6210\u529F\u8BFB\u53D6\u8003\u52E4\u8BB0\u5F55\u6761\u6570(Get AttdSyncRecords)\uFF1A")
							.append(resultList.size()).append("\uFF01\n")
							.toString();
				}
			}
		}

		return result;
	}

	static Logger logger = Logger
			.getLogger(com.wyzz.hr.bo.impl.AttdoriginaldataBOImpl.class);
	private IAttdoriginaldataDAO attdoriginaldataDAO;

}
